package cn.jiedh.app.meiweidk.browse;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.EmptyRecyclerView;
import cn.jiedh.app.meiweidk.Utils.UI.StateLayout;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.baseadapter.BaseAdapter;
import cn.jiedh.app.meiweidk.baseadapter.BaseViewHolder;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;

/**
 * @name：
 * @author： liuyun
 * @phone： 15723310658
 * @createTime： 2017/12/12
 * @modifyTime： 2017/12/12
 * @explain：说明
 */


public class OpinionFeedbackActivity extends BaseActivity {
    private static final int MAX_INPUT_WORDS_NUMBER = 140;//输入最大的字符数
    private static final int MIN_INPUT_WORDS_NUMBER = 0;//输入最小的字符数
    @BindView(R.id.bar_tv_title)
    TextView barTvTitle;
    @BindView(R.id.opinion_et)
    EditText opinionEt;
    @BindView(R.id.number_words_tv)
    TextView numberWordsTv;
    BaseAdapter<FeedBack> adapter;
    int currentExpendPosition = -1;
    List<FeedBack> list = new ArrayList<>();
    @BindView(R.id.listview)
    EmptyRecyclerView listview;
    @BindView(R.id.empty_nn_pic)
    ImageView emptyNnPic;
    @BindView(R.id.empty_nn_btn)
    TextView emptyNnBtn;
    @BindView(R.id.statelayout)
    StateLayout statelayout;
    @BindView(R.id.smartrefreshLayout)
    SmartRefreshLayout smartrefreshLayout;
    private int pageNo = 1;
    private int pageSize = 10;
    @Override
    protected int getLayoutView() {
        return R.layout.activity_opinionfeedback;
    }

    @Override
    protected void initView(View view) {
        barTvTitle.setText("意见反馈");
        opinionEt.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_INPUT_WORDS_NUMBER)});
        numberWordsTv.setText("0/" + MAX_INPUT_WORDS_NUMBER);
        statelayout.setOnNoClick(new StateLayout.NoNetView() {
            @Override
            public void setOnclck(View view) {
                smartrefreshLayout.autoRefresh();
            }
        });
        listview.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BaseAdapter<FeedBack>(this, R.layout.item_feedback, list) {
            @Override
            public void convert(BaseViewHolder holder, FeedBack bean, int position) {
                holder.setText(R.id.title_tv,bean.getFeedContent());
                holder.setText(R.id.question_time_tv,bean.getFeedDate());
                holder.setText(R.id.replay_tv,bean.getReplyContent());
                holder.setText(R.id.answer_time_tv,bean.getReplyDate());
                holder.setText(R.id.customer_service_tv,bean.getReplyPerson());

            }
        };
        listview.setLayoutManager(new LinearLayoutManager(this));
        listview.setAdapter(adapter);
        smartrefreshLayout.autoRefresh();
        smartrefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）

        refreshAndLoad();
        opinionEt.addTextChangedListener(new TextWatcher() {
            //输入表情前的光标位置
            private int cursorPos;
            //输入表情前EditText中的文本
            private String inputAfterText;
            //是否重置了EditText的内容
            private boolean resetText;
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (!resetText) {
                    cursorPos = opinionEt.getSelectionEnd();
                    // 这里用s.toString()而不直接用s是因为如果用s，
                    // 那么，inputAfterText和s在内存中指向的是同一个地址，s改变了，
                    // inputAfterText也就改变了，那么表情过滤就失败了
                    inputAfterText= s.toString();
                }

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    if (count >= 2) {//表情符号的字符长度最小为2
                        try {
                            CharSequence input = s.subSequence(start, start + count);
                            if (containsEmoji(input.toString())) {
                                resetText = true;
                                Toast.makeText(OpinionFeedbackActivity.this, "不支持输入表情符号", Toast.LENGTH_SHORT).show();
                                //是表情符号就将文本还原为输入表情符号之前的内容
                                opinionEt.setText(inputAfterText);
                                CharSequence text = opinionEt.getText();
                                if (text instanceof Spannable) {
                                    Spannable spanText = (Spannable) text;
                                    Selection.setSelection(spanText, text.length());
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            L.e("输入反馈时出错");
                        }
                    }
                } else {
                    resetText = false;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                numberWordsTv.setText(opinionEt.getText().toString().length() + "/" + MAX_INPUT_WORDS_NUMBER);
            }
        });
    }
    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }
    @Override
    protected void initData() {
}

    private void refreshAndLoad() {
        smartrefreshLayout.setOnRefreshListener(refreshLayout -> refreshLayout.getLayout().postDelayed(() -> {
            pageNo = 1;
            list.clear();
            statelayout.netviewGone();
            adapter.notifyDataSetChanged();
            getFeedBacknList(false);
            refreshLayout.finishRefresh();
            refreshLayout.setLoadmoreFinished(false);
        }, 2000));
        smartrefreshLayout.setOnLoadmoreListener(refreshLayout -> {
            refreshLayout.getLayout().postDelayed(() -> {
                pageNo++;
                getFeedBacknList(true);
                refreshLayout.finishLoadmore();
            }, 2000);

        });
    }
    public void getFeedBacknList(boolean isLoadMore) {
        Map<String,Object> args=new HashMap<>();
        args.put("pageNo", pageNo);
        args.put("pageSize", pageSize);
        request(this, UrlUtils.GET_FEEDBACK_LIST, args, false, new ResponseSuccess<FeedBackList>() {
            @Override
            public void onRequestSucceed(BaseResponse<FeedBackList> response) {
                if (response.getCode() == 0) {
                    List<FeedBack> mlist = response.getData().getDataList();
                    if(!isLoadMore) {
                        list.clear();
                    }
                    list.addAll(mlist);
//                    listview.setEmptyView(emptyview);
                    adapter.notifyDataSetChanged();
                }
            }
        }, (error, msg) -> {
//            stateLayout.netviewGone();
            list.clear();
//            listview.setEmptyView(findViewById(R.id.emptyview));
            adapter.notifyDataSetChanged();
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @OnClick(R.id.submit_btn)
    public void onViewClicked() {
        String opinion = opinionEt.getText().toString();
        if (TextUtils.isEmpty(opinion)) {
            Toast.makeText(this, "意见反馈内容不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        if (opinion.length() < MIN_INPUT_WORDS_NUMBER) {
            Toast.makeText(this, "意见反馈内容不能少于" + MIN_INPUT_WORDS_NUMBER + "个字符", Toast.LENGTH_LONG).show();
            return;
        }
        Map<String, Object> args = new HashMap<>();
        args.put("feedContent", opinion);
        args.put("timeStamp", System.currentTimeMillis());
        request(this, UrlUtils.ADD_FEEDBACK, args, false, new ResponseSuccess<Object>() {
            @Override
            public void onRequestSucceed(BaseResponse<Object> response) {
                if (response.isSuccess()) {
                    MobclickAgent.onEvent(activity,"my_help_feedback_submit");
                    Toast.makeText(OpinionFeedbackActivity.this, response.getMessage(), Toast.LENGTH_LONG).show();
                    SPUtils.saveBuried("click","7","帮助中心-用户反馈提交","",
                            "我的-帮助中心-用户反馈","","","");
                    finish();
                }
            }
        }, (error, msg) -> {
            Toast.makeText(OpinionFeedbackActivity.this, msg, Toast.LENGTH_LONG).show();
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
